<template>
  <nly-content-wrapper>
    <nly-content>
       <a-tabs type="card" style="margin-top: 40px; height: 100%;" @change="tabChange">
          <a-tab-pane key="1" tab="我的笔记">
            <div style="margin-top: 20px">
              <!-- <a-button type="primary" class="crm-btn" @click="EdiItem">编辑</a-button> -->
              <a-button type="primary" class="crm-btn" @click="deleteNote">删除</a-button>
              <a-button type="primary" class="crm-btn" @click="AddItem">新增</a-button>
            </div>
            <!-- 列表 -->
            <a-table
              :columns="columns"
              :components="components"
              :data-source="data"
              :scroll="{ x: 500, y: 500}"
              style="height: calc(100vh - 16rem);"
              bordered
              :pagination="pagination"
              @change="onTableChange"
              :row-selection="{selectedRowKeys: selectedKeys, onChange: selection}"
              >
                <template slot="content" slot-scope="text">
                  <div style="width: 100px;height: 22px;" v-html="text"></div>
                </template>
              </a-table>
          </a-tab-pane>
        </a-tabs>
        <!-- modal 弹窗  -->
        <a-modal v-model="eidtModelShow" centered on-ok="handleok" :title="editItem.id ? '编辑' : '新增'" width="960px">
        <div id="components-form-demo-advanced-search">
          <a-form
            class="ant-advanced-search-form"
            :form="form"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 18 }"
            @submit="handleSubmit"
          >
            <a-row :gutter="24">
              <a-col :span="15" :pull="3">
                <a-form-item label="标题">
                  <a-input
                    v-decorator="['title', { rules: [{ required: true, message: '标题不能为空' }] }]"
                    placeholder="请输入标题"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24" :pull="6">
                <a-form-item label="内容">
                   <div ref="editor" style="text-align:left;width: 750px;" class="editer"></div>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <template slot="footer">
          <a-button type="primary" html-type="submit" @click="handleSubmit" style="margin-right: 20px;">保存</a-button>
          <!-- <a-button :style="{ marginLeft: '8px' }" @click="handleReset">重置</a-button> -->
          <a-button :style="{ marginLeft: '8px' }" @click="() => (eidtModelShow = false)" style="margin-right: 75px;">关闭</a-button>
        </template>
      </a-modal>
    </nly-content>
  </nly-content-wrapper>
</template>

<script>
import { listToMap } from "@/utils/tool/map";
import { components } from "@/utils/antTableComponents";
import { createEditor } from "@/utils/wangEditer";
import {pageList, save, deleteNote} from "@/api/personal/userNote";

const basePostData = {
  current: 1,
  size: 20
};

export default {
  data() {
    const columns = [
      {
        title: "标题",
        dataIndex: "title",
        key: "x",
        align: "left",
        width: 300,
        customRender: (text, row) => {
           return (
            <span>
              <i class={row.title || ""} style="margin-right:5px;"></i>
              <a style="color: #000;" href="javascript:;" onClick={() => this.EdiItem(row)}>{text}</a>
            </span>
          );
        }
      },
      {
        title: "内容",
        dataIndex: "content",
        key: "content",
        width: 400,
        align: "left",
        scopedSlots: { customRender: 'content' },
      },
      {
        title: "创建时间",
        dataIndex: "createDate",
        key: "createDate",
        width: 150
      }
    ];

    //表格 头部 可伸缩
    this.components = components(columns);
    return {
      tabKey: 1,
      postData: { ...basePostData },
      data: [],
      count: 0,
      columns,
      form: this.$form.createForm(this, { name: "advanced_search" }),
      pagination: { //分页信息
        defaultPageSize: 20,
        current: 1,
        pageSize: 20,
        total: 0,
        showTotal: total => {
          return (
            <div>
              共 {total} 条数据，每页
              <a-input-number
                value={this.pagination.pageSize}
                min={1}
                max={500}
                onPressEnter={e => this.changePageSize(e)}
              />
              条
            </div>
          );
        },
        showQuickJumper: true,
        showLessItems: true
      },
      reporForm: {},
      show: false, //是否显示
      editItem: {}, //新增/编辑对象
      eidtModelShow: false,
      selectedIds: [],  //table选中id
      selectedData: [], //table选中数据
      editorContent: '',  //富文本内容
      selectedKeys: [],
      editor: null, 
    };
  },
  mounted() {
    this.PageList();
  },
  methods: {
    //tab 切换
    tabChange(key) {
      console.log(key);
      this.tabKey = key;
      this.PageList();
    },
    //添加
    AddItem() {
      this.editItem = {};
      this.handleReset();
      const {editor} = this;
      if(!editor){
        this.$nextTick(function () {
          let div =  this.$refs["editor"];
          let editorOnChange = (html) => {
            console.log("保存富文本：",html);
            this.editorContent = html
          }
          let newEditor = createEditor(div,editorOnChange);
          console.log("f富文本editor",newEditor)
          this.editor = newEditor;
          this.editor.txt.html("");
        });
      }else {
        this.editor.txt.html("");
      }
      this.eidtModelShow = true;
    },
    //编辑
    EdiItem(row) {
      let data = null;
      console.log(row);
      if(!row) {
        if (this.selectedData.length != 1) {
        this.$message.warn("请选择一条数据");
          return false;
        }else {
          data = this.selectedData[0];
        }
      }else {
        data = row;
        this.selectedIds = [];
        this.selectedData = [];
        this.selectedKeys = [];
        this.selectedData[0] = row;
        this.selectedIds[0] = row.id;
      }
    
      this.eidtModelShow = true;
      const {editor} = this;
      if(!editor){
        this.$nextTick(function () {
          let div =  this.$refs["editor"];
          let editorOnChange = (html) => {
            console.log("保存富文本：",html);
            this.editorContent = html
          }
          let newEditor = createEditor(div, editorOnChange);
          console.log("f富文本editor",newEditor)
          this.editor = newEditor;
          this.editor.txt.html(data.content);
        });
      }else {
        //文本框赋值
        this.editor.txt.html(data.content);
      }
      //form赋值
      this.form = this.$form.createForm(this, {
        mapPropsToFields: () => {
          return {
            title: this.$form.createFormField({
              value: data.title
            })
          };
        }
      });
      this.editItem = { ...data };
    },
    //删除笔记
    deleteNote() {
      if(this.selectedIds.length < 1) {
        this.$message.error("请选择要删除的笔记");
        return;
      }
      let _this = this;
      this.$confirm({
        title: '提示',
        content: '您确定要删除该笔记吗？',
        onOk() {
            deleteNote(_this.selectedIds).then(response => {
              if(response.code == 200) {
                _this.$message.success("删除成功");
                _this.PageList();
              }else {
                this.$message.error(response.message);
              }
            });
        },
        onCancel() {
        },
      });
    },
    // 获取列表
    PageList(status) {
      const { postData } = this;
      postData.type = 2
      pageList(postData).then(response => {
        if (response.code === 200) {
            const { data } = response;
            const { records, total, current, size } = data;
            this.data = records;
            Object.assign(this.pagination, {
              total
            });
          }
        }).catch(error => {});
    },
    
    //获取
    showFunction() {
      this.show = !this.show;
    },
    //表单重置
    handleReset() {
      this.form.resetFields();
    },
    //保存笔记
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          const id = this.editItem.id;
          this.editItem = { ...values };
          this.editItem.id = id;
          this.editItem.content = this.editorContent;
          console.log("开始保存:", this.editItem);
          this.editItem.createDate = null;
          this.editItem.type = 2;
          save(this.editItem)
            .then(response => {
              if (response.code === 200) {
                this.$message.success("保存成功");
                //刷新 列表
                this.PageList();
                this.selectedKeys = [];
                this.eidtModelShow = false;
              }
            })
        }
      });
    },
    //笔记table选择
    selection(keys, info) {
      this.selectedKeys = keys;
      const ids = new Array();
      info.forEach(function(val) {
        ids.push(val.id);
      });
      this.selectedIds = ids;
      this.selectedData = info;
    },
    //table分页触发
    onTableChange(pagination, filters, sorter) {
      Object.assign(this.postData, {
        current: pagination.current,
        size: pagination.pageSize
      });
      Object.assign(this.pagination, {
        current: pagination.current,
        pageSize: pagination.pageSize
      });
      this.PageList();
    },
    changePageSize(e) {
      const value = e.target.value;
      const { pagination } = this;

      console.log(e, value);
      Object.assign(this.postData, {
        size: value
      });
      Object.assign(this.pagination, {
        pageSize: Number.parseInt(value)
      });
      this.PageList();
    },
    reset() {
      this.postData = { ...basePostData };
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.detailData];
      const target = dataSource.filter(item => key === item.key)[0];
      if (target) {
        target[dataIndex] = value;
        this.detailData = dataSource;
      }
    },
    
  },
  watch: {}
};
</script>
<style lang="less" scoped>
.form-inline label {
  justify-content: left !important;
}
.ant-advanced-search-form {
  padding: 24px;
  background: #fbfbfb;
}

.ant-advanced-search-form .ant-form-item {
  display: flex;
}

.ant-advanced-search-form .ant-form-item-control-wrapper {
  flex: 1;
}

#components-form-demo-advanced-search .ant-form {
  max-width: none;
}
#components-form-demo-advanced-search .search-result-list {
  margin-top: 16px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: center;
  padding-top: 80px;
}

.ant-popover-inner {
  z-index: 2999;
}
/* .crm-btn {
  margin-left: 10px;
  margin-bottom: 10px;
} */
.div-line{
  width: 100%; 
  height: 2px; 
  background: #1890ff;

}
.search-bn{
  width: 80px;
  height: 35px;
  margin-left: 15px;
  display:block; 
  text-align: center;
  line-height: 35px;
  float: left;
  cursor: pointer;
}
::v-deep{
    .w-e-text-container{
      height: 400px !important;
    }
    .editer  .w-e-menu {
      padding: 5px 9px;
    }

  .form-inline .col {
    margin-bottom: 1.5rem !important;
  }
  .icons-list  .anticon {
    margin-right: 8px;
    font-size: 16px;
  }
}
</style>
